package com.nt.train.service.context;

import com.nt.train.annotation.RequestHandler;
import com.nt.train.enums.RequestEnum;
import com.nt.train.service.IRequestStrategy;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Component;
import java.util.Map;
/**
 * 策略核心功能,获取所有策略注解的类型
 * 并将对应的class初始化到HandlerRequestTypeContext中
 * @author hlf
 * @version 1.0
 * @date 2022/8/5 14:50
 */
@Component
public class HandlerRequestProcessor implements ApplicationContextAware {

    /**
     * 获取所有的策略加入HandlerRequestCategoryFactory属性中
     * @param applicationContext
     * @throws BeansException
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        //获取所有策略注解的Bean
        Map<String, Object> requestStrategyMap = applicationContext.getBeansWithAnnotation(RequestHandler.class);
        requestStrategyMap.forEach((k,v)->{
            RequestHandler handler = AnnotationUtils.findAnnotation(v.getClass(), RequestHandler.class);
            RequestEnum type = handler.value();
            //加入map中,type作为key
            HandlerRequestFactory.putStrategy(type.getId(),  (IRequestStrategy) v);
        });
    }
}
